/**
 * 访问鉴权中间件
 * @returns {function(*, *)}
 */
const anymatch = require('anymatch');
const authConfig = require('../config/authConfig');
const config = require('../config/config');
const encrypt = require('../utils/encryptUtil');

module.exports = () => {
    return async (ctx, next) => {
        if (ctx.session && ctx.session.loginUser) {
            await next();
        } else {

            if (anymatch(authConfig.anonymous, ctx.path)) {
                if (anymatch(authConfig.content, ctx.path)) {
                    //only anonymous interface & config url need content key
                    let _key = ctx.request.header['content-key'];
                    if (!_key || !encrypt.decrypt(_key, config.CONTENT_SALT)) {
                        console.log('---content auth failed , path : ' + ctx.path);
                        ctx.response.status = 401;
                    }else{
                        await next();
                    }
                } else {
                    await next();
                }

            } else {
                ctx.redirect('/login.html');
            }
        }

    }
}